package action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Helper;
import table.User;
import table.UserHandle;

/**
 * 用来设置用户权限的控制器
 * 参数：userid 需要设置的用户的id
 * 参数：setTo 设置成为的权限组
 */
@WebServlet("/GrantAdmin")
public class GrantAdmin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GrantAdmin() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 使用get访问该页无效
		response.getWriter().append("Please use POST method!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 管理员登录有效性验证段
		UserHandle uh = new UserHandle();
		User user = (User) request.getSession().getAttribute("user");
		if(user == null) {
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		user = uh.getUserById(user.getId());
		if(user == null || !user.getGroup().equals("admin")){
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		
		String userid = Helper.getString(request.getParameter("userid"));
		String group = Helper.getString(request.getParameter("setTo"));
		if(userid == null || group == null) {
			response.getWriter().println("<script>window.history.back(-1);alert('Error parameter!');</script>");
			return;
		}
		
		if(uh.changeGroup(userid, group)) {
			response.getWriter().println("<script>window.location.href='admin_user_manage.jsp?userid=" + userid + "';alert('Modified successfully!');</script>");
		} else {
			response.getWriter().println("<script>window.history.back(-1);alert('Can not change!');</script>");
			return;
		}
	}

}
